package controllers

import (
	"acs/management/models"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/chaosue/echo-sessions"
	"github.com/labstack/echo"
)

//ListUserHandler 获取用户列表
func ListUserHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	session := sessions.Default(c)
	manager := session.Get(models.SESSION_USER)
	if manager == nil {
		err = c.Redirect(http.StatusTemporaryRedirect, models.VIEW_LOGIN_URL)
		models.CheckError(err)
	}
	groupStr := c.Param("group")
	currentUser := manager.(models.User)
	params := fmt.Sprintf("?uid=%s&app_key=%s&app_name=%s&group_name=%s", currentUser.Username, models.Conf.AppInfo.AppKey, models.Conf.AppInfo.Appname, groupStr)
	request, requesterr := http.NewRequest(http.MethodGet, models.Conf.JumeiAuth.JumeiAuthUrl+models.API_GROUP_MEMBER_URL+params, nil)
	models.CheckError(requesterr)
	client := new(http.Client)
	respo, respoErr := client.Do(request)
	defer respo.Body.Close()
	models.CheckError(respoErr)
	var responseBody []byte
	responseBody, err = ioutil.ReadAll(respo.Body)
	models.CheckError(err)
	var memberListStruct models.MemberListStruct
	json.Unmarshal(responseBody, &memberListStruct)
	var userWithPirvilege models.UserWithPirvilege
	userWithPirvilege.PrivilegeList = models.AllUserPrivilegeList[currentUser.Username]
	userWithPirvilege.User = currentUser
	for username, member := range memberListStruct.Details {
		member.IsManager = models.IsManager(username)
	}
	c.JSON(http.StatusOK, models.ExportJson(models.Right_Status, userWithPirvilege, memberListStruct, int64(len(memberListStruct.Details))))
	return
}

//ManagerLoginSuccessHandler 登录成功
func ManagerLoginSuccessHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	session := sessions.Default(c)
	token := c.QueryParam("token")
	if token == "" {
		models.CheckError(errors.New("缺少token"))
	}
	username := c.QueryParam("username")
	session.Set(models.SESSION_USER_TOKEN, token)
	models.LoadAllUser()
	var params string
	//获取用户的基本信息。
	params = fmt.Sprintf("?uid=%s&app_key=%s&app_name=%s", username, models.Conf.AppInfo.AppKey, models.Conf.AppInfo.Appname)
	request, requesterr := http.NewRequest(http.MethodGet, models.Conf.JumeiAuth.JumeiAuthUrl+models.API_MEMBER_URL+params, nil)
	models.CheckError(requesterr)
	client := new(http.Client)
	respo, respoErr := client.Do(request)
	defer respo.Body.Close()
	models.CheckError(respoErr)
	var responseBody []byte
	responseBody, err = ioutil.ReadAll(respo.Body)
	models.CheckError(err)
	var currentuser models.User
	err = json.Unmarshal(responseBody, &currentuser)
	models.CheckError(err)
	currentuser.IsManager = models.IsManager(currentuser.Username)
	session.Set(models.SESSION_USER, &currentuser)
	session.Save()
	//跳转到主页
	err = c.Redirect(http.StatusTemporaryRedirect, models.VIEW_INDEX_URL)
	models.CheckError(err)
	return
}

// GetCurrentUserHandler 获取当前登录的用户
func GetCurrentUserHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	session := sessions.Default(c)
	currentUser := session.Get(models.SESSION_USER)
	c.JSON(http.StatusOK, currentUser)
	return
}

//UserLogoutHandler 登出
func UserLogoutHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	session := sessions.Default(c)
	session.Delete(models.SESSION_USER)
	err = session.Save()
	models.CheckError(err)
	c.JSON(http.StatusOK, models.Conf.JumeiAuth.JumeiAuthUrl+"/home/logout/?camefrom="+models.Conf.JumeiAuth.JumeiAuthBusiness)
	//由前端去注销
	return
	// request, requesterr := http.NewRequest(http.MethodGet, models.Conf.JumeiAuth.JumeiAuthUrl+"/home/logout/?camefrom="+models.Conf.AppInfo.Appname, nil)
	// models.CheckError(requesterr)
	// client := new(http.Client)
	// respo, respoErr := client.Do(request)
	// defer respo.Body.Close()
	// models.CheckError(respoErr)
	// c.Redirect(http.StatusTemporaryRedirect, models.VIEW_INDEX_URL)
	// return
}
